import React, { useEffect } from 'react'
import {Form, Input, Button, Checkbox,message } from 'antd'
import {post} from '../../../Utils/axios'
import {encrypt} from '../../../Utils/crypto'
import { history } from 'umi';
import {connect} from 'dva';
import {Url} from '@/Utils/services/url'
function form(props:any) {
        const url = Url.login
        const [form] = Form.useForm()
        const onFinish = (values: any) => {
            window.localStorage.setItem('useName',values.username)
            window.localStorage.setItem('password',values.password)

            let password = encrypt(values.password)
            post(url,{userAccount:values.username,userPwd:password}).then(res =>{
                sessionStorage.setItem('token',res.userId)
                sessionStorage.setItem('useinfo',JSON.stringify(res))
                message.success('登录成功')
                props.dispatch({
                    type:'token/saveToken',
                    payload:{
                      token:res.userId
                    }
                })
                history.push({
                    pathname:'/index'
                })
            })
        };
        useEffect(()=>{
            let username = window.localStorage.getItem('useName')
            let password = window.localStorage.getItem('password')

            if(username !== undefined && password !== undefined){
                form.setFieldsValue({
                    username:username,
                    password:password
                })
            }
        },[])
        const onFinishFailed = (errorInfo: any) => {
            message.error('请填写必填项')
        };
  return (
    <div>
        <Form
            name="basic"
            form={form}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
            >
            <Form.Item
                label="用户名"
                name="username"
                rules={[{ required: true, message: '请输入用户名!' }]}
            >
                <Input />
            </Form.Item>

            <Form.Item
                label="密码"
                name="password"
                rules={[{ required: true, message: '请输入密码!' }]}
            >
                <Input.Password />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 0, span: 24 }}>
                <Button type="primary" htmlType="submit">
                登录
                </Button>
            </Form.Item>
        </Form>
    </div>
  )
}
export default connect(({token}:any) =>{
    return token
})(form)